package com.yvan.serverless;

import com.yvan.serverless.script.ScriptService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;

public class ScriptCompiler implements InitializingBean {

    @Autowired
    private ScriptService scriptService;

    private final String folder;
    private final boolean reloadEngine;

    public ScriptCompiler(String folder, boolean reloadEngine) {
        this.folder = folder;
        this.reloadEngine = reloadEngine;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        new Thread(() -> {
            String currentDir = System.getProperty("user.dir");
            System.out.println("[" + folder + "] Current dir using System:" + currentDir);
            File wd = new File(currentDir);
            Process proc = null;
            try {
                String os = System.getProperty("os.name");
                if (os.toLowerCase().startsWith("win")) {
                    proc = Runtime.getRuntime().exec("cmd /q /k cd /d " + folder, null, wd);
                } else {
                    proc = Runtime.getRuntime().exec("/bin/bash", null, wd);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (proc != null) {
                BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
                out.println("cd " + folder);
                out.println("node node_modules/typescript/bin/tsc -w");
                try {
                    String line;
                    while ((line = in.readLine()) != null) {
                        //Watching for file changes.
                        System.out.println("\033[30m [" + folder + "] " + line + "\033[m");
                        if (reloadEngine && line.endsWith("Watching for file changes.")) {
                            try {
                                scriptService.refresh();
                                System.out.println("\033[30m ReloadEngine success! \033[m");

                            } catch (Exception e) {
                                System.out.println("\033[1;31m" + "ReloadEngine fail!" + "\033[m");
                            }
                        }
                    }
                    proc.waitFor();
                    in.close();
                    out.close();
                    proc.destroy();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
